package isanfeng.tuxiaoer.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建一个ConnectionFactory，并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.56.101");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 2. 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 3. 通过connection创建一个Channel
        Channel channel = connection.createChannel();

        // 4. 制定我们的消息投递模式：消息的确认模式
        channel.confirmSelect();
        String exchangeName = "test_consumer_exchange";
        String routingKey = "consumer.save";
        // 消息是否可达
        channel.addReturnListener((replyCode, replyText, exchange, routingKey1, properties, body) -> {
            System.err.println("---handle return---");
            System.err.println("replyCode:" + replyCode);
            System.err.println("replyText:" + replyText);
            System.err.println("exchange:" + exchange);
            System.err.println("routingKey1:" + routingKey1);
            System.err.println("properties:" + properties);
            System.err.println("body:" + body);
        });
        String msg = "hello consumer rabbit mq!";
        // 5. 发送一条消息
        System.out.println("生产端：" + msg);
        channel.basicPublish(exchangeName, routingKey, true,null, (msg).getBytes());
        channel.close();
        connection.close();
    }
}
